
//
//  AppDelegate+UPush.m
//  Coach_HaiGeEr
//
//  Created by liuchen on 2018/9/18.
//  Copyright © 2018年 海格尔. All rights reserved.
//

/*
 当app未启动时,点击推送消息,进入app会调用
  - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
 }
 
当app在后台运行时或者用户正在app当前界面时会调用
 - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
 */

#import "AppDelegate+UPush.h"
#import <objc/runtime.h>
#import "MineNewsController.h"

static char UserInfoKey;

@implementation AppDelegate (UPush)

#pragma mark ==========配置信息==========
- (void)configureUMessageWithAppKey:(NSString *)appKey launchOptions:(NSDictionary *)launchOptions{
    [UMConfigure setEncryptEnabled:YES];
    //[UMConfigure setLogEnabled:YES];//上架时需要清除
    [UMConfigure initWithAppkey:appKey channel:@"App Store"];
    //ios10接收消息的代理
    if (@available(iOS 10.0, *)) {
        [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    } else {
        // Fallback on earlier versions
    }
    UMessageRegisterEntity *entity = [[UMessageRegisterEntity alloc] init];
    if (@available(iOS 10.0, *)) {
        entity.types = UNAuthorizationOptionBadge | UNAuthorizationOptionAlert | UNAuthorizationOptionSound;
    } else {
        // Fallback on earlier versions
    }
    [UMessage registerForRemoteNotificationsWithLaunchOptions:launchOptions Entity:entity completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (launchOptions) {
            NSDictionary *remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
            if (remoteNotification) {//程序关闭情况下点击推送进入
                [self jumpToMessageVCWithDictionary:remoteNotification];
            }
        }
    }];
}

#pragma mark ==========配置别名==========
- (void)setAliasWithSelectNum:(NSInteger)selectNum{
    if (selectNum == 0) {//绑定别名
        [UMessage addAlias:[NSString stringWithFormat:@"%ld",[UserMessage sharedInstance].model.ID] type:@"USER_ID" response:^(id  _Nullable responseObject, NSError * _Nullable error) {
            
        }];
    } else if (selectNum == 1){//重置别名
        [UMessage setAlias:[NSString stringWithFormat:@"%ld",[UserMessage sharedInstance].model.ID] type:@"USER_ID" response:^(id  _Nullable responseObject, NSError * _Nullable error) {
            
        }];
    } else {//移除别名
        [UMessage removeAlias:[NSString stringWithFormat:@"%ld",[UserMessage sharedInstance].model.ID] type:@"USER_ID" response:^(id  _Nullable responseObject, NSError * _Nullable error) {
            
        }];
    }
}

#pragma mark ==========UMessage代理方法==========
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo {
    
    // 关闭友盟自带的弹出框
    [UMessage setAutoAlert:NO];
    
    [UMessage didReceiveRemoteNotification:userInfo];
    
    [self zx_setUserInfo:userInfo];
    
    // 定制自己的弹出框
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:userInfo[@"aps"][@"alert"]
                                                           delegate:self
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil];
        [alertView show];
    }
}

// iOS 10新增: 处理前台收到通知的代理方法
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler API_AVAILABLE(ios(10.0)){
    
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于前台时的远程推送接受
        //关闭友盟自带的弹出框
        [UMessage setAutoAlert:NO];
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        
    }else{
        
        //应用处于前台时的本地推送接受
    }
    
    //当应用处于前台时提示设置，需要哪个可以设置哪一个
    if (@available(iOS 10.0, *)) {
        completionHandler(UNNotificationPresentationOptionSound |
                          UNNotificationPresentationOptionBadge |
                          UNNotificationPresentationOptionAlert);
    } else {
        // Fallback on earlier versions
    }
}

//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
        withCompletionHandler:(void (^)(void))completionHandler API_AVAILABLE(ios(10.0)){
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            
            //应用处于后台时的远程推送接受(必须加这句代码应用处于运行时（前台、后台）的消息处理，回传点击数据)
            [UMessage didReceiveRemoteNotification:userInfo];
            [self jumpToMessageVCWithDictionary:nil];
        }else{
            
            //应用处于后台时的本地推送接受
        }
    } else {
        // Fallback on earlier versions
    }
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    NSLog(@"device is %@",[[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""]);
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    [UMessage sendClickReportForRemoteNotification:[self zx_getUserInfo]];
}

- (void)zx_setUserInfo:(NSDictionary *)userInfo {
    
    objc_setAssociatedObject(self, &UserInfoKey, userInfo, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSDictionary *)zx_getUserInfo {
    
    if (objc_getAssociatedObject(self, &UserInfoKey)) {
        return objc_getAssociatedObject(self, &UserInfoKey);
    } else {
        
        return nil;
    }
}

#pragma mark ==========点击推送跳转==========
- (void)jumpToMessageVCWithDictionary:(NSDictionary *)remoteNotification{//remoteNotification==nil程序前台后台  !=nil pass
    if (remoteNotification==nil&&[UserMessage sharedInstance].model.loginType ==0) {
        //接受前台后台消息后跳转
        CoachTabBarController *vc = (CoachTabBarController *)[[UIApplication sharedApplication].keyWindow rootViewController];
        [vc.selectedViewController.childViewControllers lastObject];
        if ([[vc.selectedViewController.childViewControllers lastObject] class]!=[MineNewsController class]) {
            [[vc.selectedViewController.childViewControllers lastObject].navigationController pushViewController:[[MineNewsController alloc] init] animated:YES ];
        }
    } else {
        [UserMessage sharedInstance].model.loginType = 1;
    }
    
}










@end
